package sun.cn.common.poi.builder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 工作薄构建器
 * 
 * @author sunla
 * @desc
 * @date 2017年5月2日
 */
public final class WorkBookBuilder {

	private static final Logger LOG = LoggerFactory.getLogger(WorkBookBuilder.class);
	
	private WorkBookBuilder(){}

	public static class Builder {

		private InputStream stream;

		private String fileName;

		protected Builder(InputStream stream, String name) {
			this.stream = stream;
			this.fileName = name;
		}

		/**
		 * 构建工作薄
		 * 
		 * @param stream
		 *            文件流
		 * @param filename
		 *            文件名
		 * @return
		 */
		public Workbook build() {
			if (stream == null || StringUtils.isBlank(fileName))
				throw new NullPointerException("stream is null or filename is null");
			fileName = StringUtils.lowerCase(fileName);
			try {
				if (fileName.endsWith(Constans.XLS))
					return new HSSFWorkbook(stream);
				if (fileName.endsWith(Constans.XLSX))
					return new XSSFWorkbook(stream);
			} catch (Exception e) {
				LOG.error("builderWorkBook", e);
				return null;
			} finally {
				try {
					stream.close();
				} catch (IOException e) {
					LOG.error("stream close", e);
				}
			}
			return null;
		}
	}

	public static Builder create(File file) {
		try {
			return new Builder(FileUtils.openInputStream(file), file.getName());
		} catch (IOException e) {
			LOG.error("builder create", e);
			return null;
		}
	}
	
	public static Builder create(InputStream stream,String fileName) {
			return new Builder(stream, fileName);
	}

}
